//
//  ManHuaPlayerViewController.m
//  Double
//
//  Created by 孟令博 on 15/5/26.
//  Copyright (c) 2015年 袁庆秋. All rights reserved.
//

#import "ManHuaPlayerViewController.h"
#import <AFNetworking.h>
#import "RecommentDetailModel.h"
#import "DetailView.h"
#import <UIImageView+WebCache.h>
#import "CartoonPublicModel.h"
#import "PublicDetailViewController.h"
#import "PublicImageView.h"
//#import "ManHuaPlayerSecondViewController.h"
#import "ReadCartoonViewController.h"

#import "HHAlertView.h"

#import "IntroView.h"
#import "AppDelegate.h"
#import "WeiboSDK.h"

//#import "EpisodeView.h"

#define kAppKey         @"1837158850"
#define kRedirectURI    @"http://www.sharesdk.cn"

@interface ManHuaPlayerViewController ()<UIGestureRecognizerDelegate>
@property (nonatomic, retain) UIScrollView *scroll;
@end

@implementation ManHuaPlayerViewController

- (void)dealloc
{
    [_url release];
    [_episode release];
    [_scroll release];
    [_dic release];
    [_episodeArray release];
    [_categoryArray release];
    [_fromSiteArray release];
    [_watchUserArray release];
    [_iD release];
    [super dealloc];
}
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.dic = [NSMutableDictionary dictionary];
        self.categoryArray = [NSMutableArray array];
        self.episodeArray = [NSMutableArray array];
        self.fromSiteArray = [NSMutableArray array];
        self.watchUserArray = [NSMutableArray array];
    }
    return self;
}

- (void)loadView
{
    [super loadView];
    [self startConnection];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view setBackgroundColor:[UIColor whiteColor]];
    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"fanhui.png"] style:UIBarButtonItemStylePlain target:self action:@selector(leftbuttonAction)]autorelease];
}
- (void)leftbuttonAction
{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark -
#pragma mark 数据请求
- (void)startConnection
{

    self.url = [NSString stringWithFormat:@"http://manhua.haomee.cn/?m=Cartoon&ios=23&pad=0&a=cartoonInfo&id=%@&order=1&uid=(null)", self.iD];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:_url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSData *data = operation.responseData;
        self.dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        self.episodeArray = [self.dic objectForKey:@"hua"];
        self.watchUserArray = [self.dic objectForKey:@"watchUser"];
        //数据请求之后再铺设页面
        [self createTopView];
        [self createCenterView];
        [self createBottomView];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    }];
}
#pragma mark -
#pragma mark 铺设详情页面上半部分
- (void)createTopView
{
    DetailView *detail = [[DetailView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height / 4)];
    [self.view addSubview:detail];
    [detail release];
    //显示图片
    [detail.showImage sd_setImageWithURL:[NSURL URLWithString:[self.dic objectForKey:@"cover"]] placeholderImage:[UIImage imageNamed:@"placeholder.jpg"] options:SDWebImageRetryFailed];
    //名称
    detail.titleLabel.text = [self.dic objectForKey:@"name"];
    //地区
    detail.positionLabel.text = [self.dic objectForKey:@"area"];
    //主演
    NSString *character = [self.dic objectForKey:@"artist"];
    detail.categorysLabel.text = [NSString stringWithFormat:@"主演:%@", character];
    //更新时间
    NSString *time = [self.dic objectForKey:@"update_time"];
    detail.updateLabel.text = [NSString stringWithFormat:@"更新时间:%@", time];
    //更新至11集
    detail.totalNumLabel.text = self.episode;
    //立即观看按钮
    [detail.watchBtn addTarget:self action:@selector(watchAction:) forControlEvents:UIControlEventTouchUpInside];
    //分享
    [detail.downLoadBtn addTarget:self action:@selector(shareAction:) forControlEvents:UIControlEventTouchUpInside];
}
#pragma mark -
#pragma mark 观看按钮
- (void)watchAction:(id)sender
{
    if (self.episodeArray.count == 0) {
        NSString *message = @"/因版权问题已断开资源站点,为此给各位漫友带来的不便,敬请谅解!";
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"警告" message:message delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定   ", nil];
        [alert show];
        [alert release];
    } else {
        ReadCartoonViewController *second = [[ReadCartoonViewController alloc] init];
        NSDictionary *dic = [self.episodeArray objectAtIndex:0];
        NSString *url = [dic objectForKey:@"id"];
        second.comic_id = url;
        second.hidesBottomBarWhenPushed = YES;
//        [self presentViewController:second animated:YES completion:nil];
        [self.navigationController pushViewController:second animated:YES];
        [second release];
    }
}

#pragma mark 分享
- (void)shareAction:(id)sender
{
    AppDelegate *myDelegate =(AppDelegate*)[[UIApplication sharedApplication] delegate];
    WBAuthorizeRequest *authRequest = [WBAuthorizeRequest request];
    authRequest.redirectURI = kRedirectURI;
    authRequest.scope = @"all";
    
    WBSendMessageToWeiboRequest *request = [WBSendMessageToWeiboRequest requestWithMessage:[self messageToShare] authInfo:authRequest access_token:myDelegate.wbtoken];
    request.userInfo = @{@"ShareMessageFrom": @"SendMessageToWeiboViewController",
                         @"Other_Info_1": [NSNumber numberWithInt:123],
                         @"Other_Info_2": @[@"obj1", @"obj2"],
                         @"Other_Info_3": @{@"key1": @"obj1", @"key2": @"obj2"}};
    [WeiboSDK sendRequest:request];
}
#pragma mark -
#pragma mark 铺设中间“播放源”和“大家也在看”
- (void)createCenterView
{
    //大家也在看
    UILabel *publicLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, self.view.frame.size.height / 4 + 20, self.view.frame.size.width / 3, 40)];
    publicLabel.text = @"大家也在看:";
    [self.view addSubview:publicLabel];
    [publicLabel release];
    for (int i = 0; i < self.watchUserArray.count; i++) {
        PublicImageView *showImage = [[PublicImageView alloc] initWithFrame:CGRectMake((self.view.frame.size.width / 3 + 10) + i * (self.view.frame.size.width / 15 * 2 - 2), self.view.frame.size.height / 4 + 20, 40, 40)];
        showImage.userInteractionEnabled = YES;
        showImage.clipsToBounds = YES;
        showImage.layer.cornerRadius = 20;
        
        showImage.dic= [self.watchUserArray objectAtIndex:i];
        NSString *imageString = [showImage.dic objectForKey:@"head_pic"];
        [showImage sd_setImageWithURL:[NSURL URLWithString:imageString] placeholderImage:[UIImage imageNamed:@"placeholder.jpg"] options:SDWebImageRetryFailed];
        showImage.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
        [showImage addGestureRecognizer:tap];
        [self.view addSubview:showImage];
        [showImage release];
    }
}
#pragma mark -
#pragma mark 创建下面的介绍和播放界面
- (void)createBottomView
{
    UIButton *introBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height / 4 + 100, self.view.frame.size.width / 2, 30)];
    [introBtn setTitle:@"简介" forState:UIControlStateNormal];
    [introBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [introBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
    [introBtn setBackgroundColor:[UIColor lightGrayColor]];
    [introBtn addTarget:self action:@selector(introViewShow:) forControlEvents:UIControlEventTouchUpInside];
    introBtn.alpha = 0.7;
    [self.view addSubview:introBtn];
    [introBtn release];
    
    UIButton *epiBtn = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 2, self.view.frame.size.height / 4 + 100, self.view.frame.size.width / 2, 30)];
    [epiBtn setTitle:@"剧集列表" forState:UIControlStateNormal];
    [epiBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [epiBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
    [epiBtn setBackgroundColor:[UIColor lightGrayColor]];
    [epiBtn addTarget:self action:@selector(episodeViewShow:) forControlEvents:UIControlEventTouchUpInside];
    epiBtn.alpha = 0.7;
    [self.view addSubview:epiBtn];
    [epiBtn release];
    
    self.introView = [[IntroView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height / 2 , self.view.frame.size.width, self.view.frame.size.height / 2)];
    [self.introView zidingyiScroll:[self.dic objectForKey:@"intro"]];

    self.scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height / 2, self.view.frame.size.width, self.view.frame.size.height / 2)];
    
    [self.view addSubview:self.scroll];
    [self.view addSubview:self.introView];
    [self.introView release];
    [self.scroll release];
}
- (void)introViewShow:(id)sender
{
    self.scroll.alpha = 0;
    self.introView.alpha = 1;
    [self.view insertSubview:self.introView aboveSubview:self.scroll];
}

- (void)episodeViewShow:(id)sender
{
    self.scroll.contentSize = CGSizeMake(self.view.frame.size.width, 40 * (self.episodeArray.count / 4) + 50 );
    [self.view insertSubview:self.scroll aboveSubview:self.introView];
    self.introView.alpha = 0;
    self.scroll.alpha = 1;
    self.scroll.backgroundColor = [UIColor whiteColor];
    NSInteger count = self.episodeArray.count;
    CGFloat width = self.view.frame.size.width / 5;
    for (int i = 0; i < count; i++) {
        UIButton *playBtn = [[UIButton alloc] initWithFrame:CGRectMake(10 + i % 4 *(width + 10), 20 + i / 4 * 40, width, 30)];
        [playBtn setTitle:[NSString stringWithFormat:@"第%d集", i + 1] forState:UIControlStateNormal];
        [playBtn.layer setBorderWidth:2.0f];
        playBtn.layer.cornerRadius = 5;
        [playBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [playBtn setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
        playBtn.titleLabel.font = [UIFont systemFontOfSize:12];
        [playBtn setBackgroundColor:[UIColor whiteColor]];
        [playBtn setTitleColor:[UIColor orangeColor] forState:UIControlStateHighlighted];
        [playBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [playBtn addTarget:self action:@selector(playFilmBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        playBtn.tag = i + 1;
        [self.scroll addSubview:playBtn];
        [playBtn release];
    }
}
#pragma mark -
#pragma mark 点击选集数，播放视频
- (void)playFilmBtnClick:(id)sender
{
    UIButton *btn = (UIButton *)sender;
    NSDictionary *dic = [self.episodeArray objectAtIndex:btn.tag - 1];
    NSString *url = [dic objectForKey:@"id"];
    ReadCartoonViewController *play = [[ReadCartoonViewController alloc] init];
    play.comic_id = url;
    [self presentViewController:play animated:YES completion:nil];
    [play release];
}

#pragma mark -
#pragma mark 点击播放源“优酷”图标，播放视频方法
- (void)playFilmAction:(id)sender
{
    
}

#pragma mark -
#pragma mark 所有观众头像点击进入观众主页
- (void)tapAction:(UITapGestureRecognizer *)tap
{
    
}



#pragma mark -
#pragma Internal 分享的内容

- (WBMessageObject *)messageToShare
{
    WBMessageObject *message = [WBMessageObject message];
    
    message.text = [NSString stringWithFormat:@"我正在用“漫吧”观看 %@ .海量高清动漫应有尽有，漫友们快来这里团聚吧！链接:%@", [self.dic objectForKey:@"name"], _url];
    
    
    
    
    return message;
}

@end
